package com.yxt.shecaiyun.controller;
//认证相关（登录/注册/登出）

import com.yxt.shecaiyun.common.R;
import com.yxt.shecaiyun.config.JwtUtil;
import com.yxt.shecaiyun.dto.userDto.UserLoginDTO;
import com.yxt.shecaiyun.dto.userDto.UserRegisterDTO;
import com.yxt.shecaiyun.entity.User;
import com.yxt.shecaiyun.service.UserService;
import jakarta.validation.Valid;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private final UserService userService;
    private final BCryptPasswordEncoder passwordEncoder;

    public AuthController(UserService userService) {
        this.userService = userService;
        this.passwordEncoder = new BCryptPasswordEncoder();
    }

    /**
     * 用户注册
     * POST /api/auth/register
     * 参数：{
     *   "account": "test001",
     *   "password": "123456",
     *   "userNumber": "20230001",
     *   "userName": "张三",
     *   "email": "test@example.com"
     * }
     */
    @PostMapping("/register")
    public R register(@Valid @RequestBody UserRegisterDTO dto) {
        System.out.println(dto); // 查看是否打印
        // 校验账号唯一性
        if (userService.existsByAccount(dto.getUserAccount())) {
            return R.fail("用户账号已存在");
        }
        // 校验学号唯一性

        System.out.println(userService.existsByUserID(dto.getUserNumber()));
        if (userService.existsByUserID(dto.getUserNumber())) {
            return R.fail("学号已被注册");
        }
        User user = new User();
        user.setAccount(dto.getUserAccount());
        user.setPassword(passwordEncoder.encode(dto.getUserPassword()));
        user.setNumber(dto.getUserNumber());
        user.setUserName(dto.getUserName());
        user.setActive(1); // 默认启用账户
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        userService.save(user);
        User resUser = userService.findByAccount(dto.getUserAccount());
        return R.success(resUser);
    }

    /**
     * 用户登录
     * POST /api/auth/login
     * 参数：{
     *   "account": "test001",
     *   "password": "123456"
     * }
     */
    @PostMapping("/login")
    public R login(@Valid @RequestBody UserLoginDTO dto) {
        User user = userService.findByAccount(dto.getAccount());
        // 校验账户存在性
        if (user == null) {
            return R.fail("账号不存在");
        }

        // 校验账户状态
        if (user.getActive() == 0) {
            return R.fail("账户已被禁用");
        }

        // 验证密码
        if (!passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
            System.out.println(dto.getPassword() + user.getPassword());
            return R.fail("密码错误");
        }

        // 生成JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createToken(claims);
        // 构建返回数据（严格对应数据库字段）
        Map<String, Object> userInfo = new LinkedHashMap<>();
        userInfo.put("userId", user.getId());
        userInfo.put("userAccount", user.getAccount());
        userInfo.put("userName", user.getUserName());
        userInfo.put("userNumber", user.getNumber());
        userInfo.put("userMajor", user.getMajor());
        userInfo.put("token", token);
        userInfo.put("avatar", user.getAvatar());

        return R.success(userInfo);
    }
}